<?php

namespace App\Http\Controllers;

use App\Http\Requests\RegisterPost;
use App\Models\UserDetail;
use App\Models\UserInfo;
use App\Models\Users;
use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;

class ApiAuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     * 要求附带email和password（数据来源users表）
     *
     * @return void
     */
    public function __construct()
    {
        // 这里额外注意了：官方文档样例中只除外了『login』
        // 这样的结果是，token 只能在有效期以内进行刷新，过期无法刷新
        // 如果把 refresh 也放进去，token 即使过期但仍在刷新期以内也可刷新
        // 不过刷新一次作废
        $this->middleware('jwt.auth', ['except' => ['login', 'refresh', 'register']]);
        // 另外关于上面的中间件，官方文档写的是『auth:api』
        // 但是我推荐用 『jwt.auth』，效果是一样的，但是有更加丰富的报错信息返回
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['mobile', 'password']);

        if (!$token = auth('api')->attempt($credentials)) {
            return response()->json(['msg' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth('api')->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth('api')->logout();

        return response()->json(['msg' => '用户已退出']);
    }

    /**
     * Refresh a token.
     * 刷新token，如果开启黑名单，以前的token便会失效。
     * 值得注意的是用上面的getToken再获取一次Token并不算做刷新，两次获得的Token是并行的，即两个都可用。
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }

    /**
     * @param RegisterPost $request
     * @return array
     */
    public function register(RegisterPost $request)
    {
        $users = new Users();
        $users->mobile = $request->get('mobile');
        $users->password = bcrypt($request->get('password'));
        DB::beginTransaction();
        if ($users->save()) {
            // user_info 添加默认数据
            $userInfo = new UserInfo();
            $userInfo->user_id = $users->id;
            $userInfo->nickname = 'u_' . time();
            if (!$userInfo->save()) {
                DB::rollBack();
                return response()->json(['msg' => '注册失败，请重试'], 404);
            }
            // user_details 添加默认数据
            $userDetail = new UserDetail();
            $userDetail->user_id = $users->id;
            if (!$userDetail->save()) {
                DB::rollBack();
                return response()->json(['msg' => '注册失败，请重试'], 404);
            }

            DB::commit();
            return ['msg' => '注册成功'];
        }
        DB::rollBack();
        return response()->json(['msg' => '注册失败，请重试'], 404);

//        if ($data = $user->create($request->all())) {
//            return $this->jsonResultOk(['id' => $data->id]);
//        }
    }
}
